// 用户数据模块
import http from '@/shop/request/index'
import store from '@/shop/store'
import tools from '@/shop/utils/tools'
import wechat from '@/shop/wechat/wechat'
import share from '@/shop/share'

const state = {
	token: uni.getStorageSync("token") || "",
	isLogin: uni.getStorageSync("isLogin") || false, // 是否登陆
	userInfo: uni.getStorageSync("userInfo") || {}, // 用户信息
	agentInfo: {}, //分销商信息
	userData: {}, //用户其他相关信息
	isLogout:false,
	subscribeMessageIdsMap: [], //小程序订阅消息模板ids
	authType: '' // smsLogin:手机号登录注册, accountLogin:密码登录, forgotPwd:忘记密码, changePwd:修改密码, bindMobile:绑定手机号
}

const getters = {
	token: state => state.token,
	isLogin: state => state.isLogin,
	userInfo: state => state.userInfo,
	agentInfo: state => state.agentInfo,
	userOtherData: state => state.userData,
	authType: state => state.authType,
	subscribeMessageIdsMap: state => state.subscribeMessageIdsMap
}

const actions = {
	// 获取用户信息
	getUserInfo({
		commit,
		dispatch,
		getters,
		state
	}, token = '') {
		return new Promise((resolve, reject) => {
			token && uni.setStorageSync('token', token);
			http('user.info').then(res => {
					if (res.code === 200) {
						let data = {
							address: res.data.address,
							name: res.data.name,
							roleName: res.data.roleName,
							sex: res.data.sex,
							token: token,
							userid: res.data.id,
							phone: res.data.phone
						}
						commit('userInfo', res.data);
						commit('isLogin', true);

						// !lastLoginStatus && share.setShareInfo();
						// // 存在分享信息 添加分享记录
						// let spm = uni.getStorageSync('spm');
						// if (spm) {
						// 	http('common.shareAdd', {
						// 		spm: spm
						// 	});
						// 	uni.removeStorageSync('spm');
						// }
						resolve(res.data)
					}

				}).then(() => {
					// 只有在登录的时候请求购物车信息，订单信息，获取登录信息之后。
					// token && dispatch('getCartList');
					// token && dispatch('getUserData');
				})
				.catch(e => {
					reject(e)
				})
		})
	},
	// 用户其他相关信息
	getUserData({
		commit
	}) {
		return new Promise((resolve, reject) => {
			http('user.userData').then(res => {
				commit('USER_DATA', res.data);
				resolve(res)
			}).catch(e => {
				reject(e)
			})
		})
	},



	// 自动登录
	async autoLogin({
		getters,
		dispatch
	}) {
		if (getters.initWechat?.autologin && !getters.isLogin) { // 微信开启自动登录 并且当前未登录，进入自动登录流程
			let token = '';
			// #ifdef H5
			wechat.login();
			// #endif
			// #ifdef MP-WEIXIN
			token = await wechat.getWxMiniProgramSessionKey(true);
			// #endif
			token && await dispatch('getUserInfo', token);
		} else if (getters.isLogin) { // 已经登录，直接获取用户信息
			await dispatch('getUserInfo');
		}
		share.setShareInfo();
		// 初始化小程序session_key
		// #ifdef MP-WEIXIN
		if (!getters.initWechat?.autologin) {
			await wechat.getWxMiniProgramSessionKey(false);
		}
		// #endif
	},


	// 退出登录
	logout({
		commit,
		state,
		dispatch
	}) {
		
	  if(state.isLogin)
	  {
		uni.getStorageSync('token') && http('user.logout');
		commit('token', "");
		commit('isLogout',true);
		uni.removeStorageSync('chatSessionId');
		commit('isLogin', false);
		commit('userInfo', {});
		// commit('CART_LIST', []);
		commit('USER_DATA', {});
		uni.clearStorageSync();
		// 重置全局分享信息
		share.setShareInfo();
		uni.showToast({
			title: '登录过期，请重新登录',
			icon: 'none',
			duration: 2000,
			mask: true,
			success()
			{
				setTimeout(()=>{
					commit('isLogout',false);
					uni.redirectTo({
						url:'/pages/login/login'
					}) 
				},2000)
			 
			
			}
		});
		
	  }else{
		
		  if(!state.isLogout)
		  {
			 commit('isLogout',true);
			 uni.showToast({
			 	title: '您还未登录，请登录',
			 	icon: 'none',
			 	duration: 2000,
			 	mask: true,
			 	success()
			 	{
					setTimeout(()=>{
						commit('isLogout',false);
						uni.redirectTo({
							url:'/pages/login/login'
						}) 
					},2000)
			 	}
			 }); 
		  }
		 
	  }
		
		
		
		
	},
	checkHouse() {
		if (uni.getStorageSync('token')) {
			http('lhouse.query').then(r => {
				if (r.code == 200) {
				
					if (!(r.data.project && r.data.project.projectId)) {
						uni.showToast({
							icon:'none',
							title: '请首先新增房屋信息',
							duration: 2000,
							success: () => {
								setTimeout(() => {
									uni.navigateTo({
										url: '/pages/index/editHourse'
									})
								})

							}
						});

					}
				}
			})
		};
	}


}

const mutations = {
	token(state, payload) {
		state.token = payload;
		uni.setStorageSync("token", payload);
	},
	// 登录态
	isLogin(state, data) {
		state.isLogin = data;
		uni.setStorageSync('isLogin', data);
	},
	isLogout(state, data)
	{
		state.isLogout = data;
	},
	// 用户信息
	userInfo(state, data) {
		state.userInfo = data;
		uni.setStorageSync("userInfo", data);
	},

	// 小程序订阅消息模板ids
	MESSAGE_IDS(state, data) {
		state.subscribeMessageIds = data;
	},
	USER_DATA(state, data) {
		state.userData = data;
	},


	// 订阅消息
	subscribeMessage(state, type) {
		let arr = state.subscribeMessageIdsMap[type];
		arr.length && uni.requestSubscribeMessage({
			tmplIds: arr,
			success: (res) => {
				console.log(res);
			},
			fail: (err) => {
				console.log(err);
			}

		});
	},


}



export default {
	state,
	mutations,
	actions,
	getters
}
